package com.dx.membercenterbe.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.dx.membercenterbe.common.BaseResponse;
import com.dx.membercenterbe.common.ErrorCode;
import com.dx.membercenterbe.common.ResultUtils;
import com.dx.membercenterbe.exception.BusinessException;
import com.dx.membercenterbe.model.domain.dto.UserInfoDto;
import com.dx.membercenterbe.model.domain.entity.User;
import com.dx.membercenterbe.model.domain.request.CreateUserRequest;
import com.dx.membercenterbe.model.domain.request.UserLoginRequest;
import com.dx.membercenterbe.model.domain.request.UserRegisterRequest;
import com.dx.membercenterbe.model.enums.UserRoleType;
import com.dx.membercenterbe.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

import static com.dx.membercenterbe.constant.UserConstant.USER_LOGIN_STATE;

@RestController
@RequestMapping("/user")
//跨域问题解决、默认全部ip都可以访问，
@CrossOrigin(origins = "http://localhost:5173", allowCredentials = "true")
public class UserController {

    @Resource
    private UserService userService;

    /**
     * 用户注册
     *
     * @param userRegisterRequest  前端请求注册参数
     * @return
     */
    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        if (userRegisterRequest == null) {
//            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        String planetCode = userRegisterRequest.getPlanetCode();
        if (StringUtils.isAllBlank(userAccount, userPassword, checkPassword,planetCode)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long userId = userService.regestAccount(userAccount, userPassword, checkPassword,planetCode);
        return ResultUtils.success(userId);
    }

    /**
     * 管理员新增用户
     *
     * @param createUserRequest 创建用户参数
     * @return
     */
    @PostMapping("/create")
    public BaseResponse<Long> createUser(@RequestBody CreateUserRequest createUserRequest) {
        if (createUserRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = createUserRequest.getUserAccount();
        String userPassword = createUserRequest.getUserPassword();
        String checkPassword = createUserRequest.getCheckPassword();
        String planetCode = createUserRequest.getPlanetCode();
        if (StringUtils.isAllBlank(userAccount, userPassword, checkPassword,planetCode)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数存在空情况");
        }
        long userId = userService.createUser(createUserRequest);
        return ResultUtils.success(userId);
    }

    /**
     * 用户登录
     *
     * @param userLoginRequest 前端请求登录参数
     * @param httpServletRequest
     * @return
     */
    @PostMapping("/login")
    public BaseResponse<User> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest httpServletRequest) {
        if (userLoginRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"");
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if (StringUtils.isAllBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数存在空参数");
        }
        User saftyUser = userService.userLogin(userAccount, userPassword, httpServletRequest);
        return ResultUtils.success(saftyUser);
    }

    /**
     * 用户注销
     *
     * @param httpServletRequest
     * @return
     */
    @PostMapping("/logout")
    public BaseResponse<Integer> userLogout(HttpServletRequest httpServletRequest) {
        if (httpServletRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        int userLogout = userService.userLogout(httpServletRequest);
        return ResultUtils.success(userLogout);
    }

    @GetMapping("/current")
    public BaseResponse<User> getCurrentUser(HttpServletRequest httpServletRequest){
        Object userObj = httpServletRequest.getSession().getAttribute(USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        if(currentUser == null){
            throw new BusinessException(ErrorCode.NOT_LOGIN,"用户未登录");
        }
        //如果不需要null值、且追求性能，建议使用long。
        //如果需要null值或者需要与泛型、集合类配合使用，使用Long。
        long currentUserId = currentUser.getId();//如果需要使用集合类（如List<Long>）
        //todo 校验用户是否合法（是否异常账户）
        User user = userService.getById(currentUserId);
        User saftyUser = userService.getSaftyUser(user);
        return ResultUtils.success(saftyUser);
    }

    /**
     * 管理员查询
     *
     * @param username 用户名
     * @param httpServletRequest
     * @return
     */
    @GetMapping("/search")
    public BaseResponse<List<User>> searchUser(String username,HttpServletRequest httpServletRequest){
        //鉴权，非管理员，抛出空数组
        if(!userService.isAdminUser(httpServletRequest)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //查询
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(username)) {
            queryWrapper.like("username", username);
        }
        List<User> userList = userService.list(queryWrapper);
        List<User> saftyuserlist = userList.stream().map(user -> userService.getSaftyUser(user)).collect(Collectors.toList());
        return ResultUtils.success(saftyuserlist);
    }

    /**
     * 管理员逻辑删除用户
     *
     * @param id 用户id
     * @param httpServletRequest
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteUser(@RequestBody long id, HttpServletRequest httpServletRequest){
        //鉴权，非管理员，抛出空数组
        if(!userService.isAdminUser(httpServletRequest)){
            throw new BusinessException(ErrorCode.NO_AUTH,"非管理无权限");
        }
        if(id<=0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        boolean b = userService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 修改用户权限
     *
     * @param
     * @return
     */
    @PostMapping("/changerole")
    public BaseResponse<Boolean> changeRole(@RequestParam String userAccount,@RequestParam int userRole) {
        //判断空值
        if(StringUtils.isAllBlank(userAccount)){
            throw new BusinessException(ErrorCode.NULL_ERROR,"修改账号为空");
        }
        //查找用户
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("userAccount",userAccount)
                .set("userRole",userRole);
        //更新
        boolean updateSuccess  = userService.update(null, updateWrapper);

        if(!updateSuccess){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"修改权限失败，参数错误");
        }
        return ResultUtils.success(updateSuccess);
    }
    /**
     * 修改用户信息
     *
     * @param
     * @return
     */
    @PostMapping("/change-info")
    public BaseResponse<Boolean> changeInfo(@RequestBody UserInfoDto userInfoDto) {
        //判断空值
        if(userInfoDto == null){
            throw new BusinessException(ErrorCode.NULL_ERROR,"");
        }
        //查找用户
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("userAccount",userInfoDto.getUserAccount());
        // 根据字段的非空性进行更新
        if (userInfoDto.getUserName() != null) {
            updateWrapper.set("userName", userInfoDto.getUserName());
        }
        if (userInfoDto.getAvatarUrl() != null) {
            updateWrapper.set("avatarUrl", userInfoDto.getAvatarUrl());
        }
        if (userInfoDto.getGender() != null) {
            updateWrapper.set("gender", userInfoDto.getGender());
        }
        if (userInfoDto.getPhone() != null) {
            updateWrapper.set("phone", userInfoDto.getPhone());
        }
        if (userInfoDto.getEmail() != null) {
            updateWrapper.set("email", userInfoDto.getEmail());
        }
        //更新
        boolean updateSuccess  = userService.update(null, updateWrapper);
        if(!updateSuccess){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"更新失败");
        }
        return ResultUtils.success(updateSuccess);
    }
    /**
     * 修改用户信息
     *
     *
     * @param
     * @return 返回值大于1，修改成功
     */
    @PostMapping("/update")
    public BaseResponse<Integer> updateUser(@RequestBody User user,HttpServletRequest httpServletRequest) {
        //判断参数
        if(user == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数为空");
        }
        //校验权限,,在service种做了校验
        User loginUser = userService.getLoginUser(httpServletRequest);

        //触发更新
        int res = userService.updateUser(user,loginUser);
        return ResultUtils.success(res);
    }




    /**
     * 根据标签搜索用户
     * @param tagNameList 标签列表
     * @return 返回用户列表
     */
    @GetMapping("/search/tags")
    private BaseResponse<List<User>> searchUserByTags(@RequestParam(required = false) List<String> tagNameList){
        if (CollectionUtils.isEmpty(tagNameList)){
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        List<User> users = userService.searchUserByTags(tagNameList);
        return ResultUtils.success(users);

    }
}
